package com.etoak.service.impl;

import cn.hutool.crypto.digest.MD5;
import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.etoak.common.core.constant.CommonConstant;
import com.etoak.common.core.exception.CustomException;

import com.etoak.common.jwt.MyJwtUtil;
import com.etoak.common.redis.service.RedisService;
import com.etoak.dto.LoginDTO;
import com.etoak.entity.User;
import com.etoak.mapper.UserMapper;
import com.etoak.service.UserService;
import com.etoak.vo.TokenVO;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author etoak
 * @since 2025-07-30
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    RedisService redisService;

    @Override
    public TokenVO login(LoginDTO loginDTO) {
        /**
         * 1. 验证code
         * 这里的redis的key是从CodeController中生成的
         */
        String code = redisService.get(CommonConstant.CODE_REDIS_KEY_PREFIX + loginDTO.getUuid());
        if(!StringUtils.equalsIgnoreCase(code, loginDTO.getCode())){
            throw new CustomException("验证码错误或已失效！");
        }

        /**
         * 2. 验证用户名密码
         * 用了md5加密算法
         */
        String password = MD5.create().digestHex(loginDTO.getPassword());
        User user = lambdaQuery()
                .eq(User::getUsername, loginDTO.getUsername())
                .eq(User::getPassword, password)
                .one();

        if(ObjectUtils.isEmpty(user)){
            throw new CustomException("用户名或密码错误!");
        }

        /**
         * 3. 验证JWT - Json Web Toke
         */

        Map<String, Object> claimsMap = new HashMap<>();
        claimsMap.put("username",user.getUsername());
        claimsMap.put("id",user.getId());
        String jwt = MyJwtUtil.create(claimsMap);
        return new TokenVO(user.getUsername(),jwt);
    }

}
